package com.yf.tool;

import cn.hutool.core.bean.BeanUtil;
import com.yf.mapper.system.SysUserMapper;
import com.yf.tool.context.ToolBaseContext;
import com.yf.tool.model.dto.RequestInfoDTO;
import com.yf.utils.AddressUtil;
import eu.bitwalker.useragentutils.UserAgent;
import lombok.RequiredArgsConstructor;
import org.springframework.ai.chat.model.ToolContext;
import org.springframework.stereotype.Component;

import java.util.function.BiFunction;
import java.util.function.Function;

/**
 * 用户基础信息工具
 *
 * @author : YiFei
 * @since : 2025/5/21 0:22
 */
@Component
@RequiredArgsConstructor
public class ClientEnvironmentInfoTool implements BiFunction<Void, ToolContext, RequestInfoDTO> {

    @Override
    public RequestInfoDTO apply(Void unused, ToolContext toolContext) {
        ToolBaseContext toolContextDTO = BeanUtil.toBean(toolContext.getContext(), ToolBaseContext.class);
        String geoLocation = AddressUtil.getRealAddressByIP(toolContextDTO.getIp());
        UserAgent parsedAgent = UserAgent.parseUserAgentString(toolContextDTO.getHeaderUserAgent());

        return RequestInfoDTO.builder()
                .ip(toolContextDTO.getIp())
                .address(geoLocation)
                .browser(parsedAgent.getBrowser().getName())
                .operatingSystem(parsedAgent.getOperatingSystem().getName())
                .build();
    }
}
